package cn.micro.system.manage.common.security.filter;

import cn.micro.system.manage.common.component.RedisService;
import cn.micro.system.manage.common.constants.SecurityConstants;
import cn.micro.system.manage.common.result.Result;
import cn.micro.system.manage.common.result.ResultCodeEnum;
import cn.micro.system.manage.common.security.config.IgnoreUrlsConfig;
import cn.micro.system.manage.common.utils.JwtHelper;
import cn.micro.system.manage.common.utils.ResponseUtil;
import cn.micro.system.manage.entity.vo.LoginUserDetailVO;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//认证解析过滤器
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private RedisService redisService;

    private IgnoreUrlsConfig ignoreUrlsConfig;

    private JwtHelper jwtHelper;

    public TokenAuthenticationFilter(RedisService redisService,IgnoreUrlsConfig ignoreUrlsConfig,JwtHelper jwtHelper) {
        this.redisService = redisService;
        this.ignoreUrlsConfig = ignoreUrlsConfig;
        this.jwtHelper = jwtHelper;

    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        logger.info("uri:"+request.getRequestURI());
        //如果是登录接口，直接放行
        if(SecurityConstants.LOGIN_PATH.equals(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }

        //对白名单进行放行--并且移除请求头的认证信息
        String requestURI = request.getRequestURI();
        //路径匹配
        if (ignoreUrlsConfig.getUrls().stream().anyMatch(requestURI::contains)) {
            //移除请求头授权信息
            request.removeAttribute(SecurityConstants.TOKEN_KEY);
            chain.doFilter(request, response);
            return;
        }

        try {
            UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
            if(null != authentication) {
                SecurityContextHolder.getContext().setAuthentication(authentication);
                chain.doFilter(request, response);
            } else {
                ResponseUtil.writeErrMsg(response, ResultCodeEnum.FORBIDDEN);
            }
        }catch (Exception e){
            ResponseUtil.writeErrMsg(response, ResultCodeEnum.UNAUTHORIZED);
        }
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token置于header里
        String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
        logger.info("authorizationHeader:"+authorizationHeader);
        if (!StringUtils.isEmpty(authorizationHeader) && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
            // 解析&验证 JWT
            Claims claims = this.jwtHelper.parseAndValidateToken(token);
            LoginUserDetailVO loginUserDetail = jwtHelper.getLoginUserDetail(claims);
            logger.info("useruame:"+loginUserDetail.getUsername());
            if (!StringUtils.isEmpty(loginUserDetail.getUsername())) {
                String authoritiesString = (String) redisService.get(loginUserDetail.getUsername());
                List<Map> mapList = JSON.parseArray(authoritiesString, Map.class);
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                for (Map map : mapList) {
                    authorities.add(new SimpleGrantedAuthority((String)map.get("authority")));
                }
                return new UsernamePasswordAuthenticationToken(loginUserDetail, null, authorities);
            }
        }
        return null;
    }
}
